package br.usjt.lab.hirose;

import javax.swing.*;
import java.awt.*;

public class FloodFill extends JComponentWithEvents {
	
	private static final long serialVersionUID = 1L;
	private Color[][] board;
	private int rows = getHeight()/2, cols = getWidth()/2;
	private boolean floodFillMode = false;

	public void start() {
		reset();
	}

	public void reset() {
		board = new Color[rows][cols];
		for (int row = 0; row < rows; row++)
			for (int col = 0; col < cols; col++)
				board[row][col] = Color.blue;
	}

	public void keyPressed(char key) {
		if (key == 'r')
			reset();
		else if (key == 'm')
			floodFillMode = !floodFillMode;
	}

	public void mouseDragged(int x, int y) {
		if (floodFillMode == false)
			mouse(x, y);
	}

	public void mousePressed(int x, int y) {
		if (floodFillMode == true)
			floodFill(x, y);
		else
			mouse(x, y);
	}

	public void floodFill(int x, int y) {
		int size = getGridSize();
		int col = x / size;
		int row = y / size;
		Color oldColor = board[row][col];
		Color newColor = Color.red; // Color.red;
		floodFill(row, col, oldColor, newColor);
	}

	public void floodFill(int row, int col, Color oldColor, Color newColor) {
		if ((row < 0) || (row >= rows) || (col < 0) || (col >= cols)
				|| (!oldColor.equals(board[row][col])))
			return;
		else {
			// recursive case
			board[row][col] = newColor;
			int gray = newColor.getRed() - 5;
			if (gray < 0)
				gray = 0;
			newColor = new Color(gray, gray, gray);
			floodFill(row - 1, col, oldColor, newColor); // above
			floodFill(row + 1, col, oldColor, newColor); // below
			floodFill(row, col + 1, oldColor, newColor); // right
			floodFill(row, col - 1, oldColor, newColor); // left
		}
	}

	public void mouse(int x, int y) {
		int size = getGridSize();
		int col = x / size;
		int row = y / size;
		board[row][col] = Color.orange;
	}

	public void paint(Graphics2D page) {
		for (int row = 0; row < rows; row++)
			for (int col = 0; col < cols; col++)
				paintCell(page, row, col);
	}

	public int getGridSize() {
		int rowSize = getHeight() / rows;
		int colSize = getWidth() / cols;
		int size = Math.min(rowSize, colSize);
		return size; 
	}

	public void paintCell(Graphics2D page, int row, int col) {
		int size = getGridSize();
		int left = size * col;
		int top = size * row;
		page.setColor(board[row][col]);
		page.fillRect(left, top, size, size);
		page.setColor(Color.black);
		page.drawRect(left, top, size, size);
	}

	public static void main(String[] args) {
		launch(500, 400);
	}
}
